const { processImageUrl } = require("../../../utils/image");
const request = require('../../../utils/request.js');
const app = getApp();

Page({
  data: {
    id: null,
    name: '',
    image: '',
    imageUrl: '',
    shortDescription: '',
    growthCycle: '',
    fullDescription: '',
    suggestion: '',
    precautions: ''
  },

  onLoad(options) {
    if (options.id) {
      this.setData({ id: options.id });
      this.loadDetail();
    }
  },

  // 加载详情
  loadDetail() {
    // 模拟加载数据
    request.request({
      url: `${app.globalData.baseUrl}/api/agricultural-knowledge/residues/${this.data.id}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${app.getGlobalToken()}`
      },
      success: (res) => {
        const data = res.data.data
        this.setData({
          imageUrl: processImageUrl(data.image),
          ...data,
        })
      },
      fail: (err) => {
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
        console.error('加载文章详情失败:', err)
      },
      complete: () => {
        //
      }
    })
  },

  // 选择图片
  chooseImage() {
    let me = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: `${app.globalData.baseUrl}/api/files/upload`,
          filePath: tempFilePaths[0],
          name: 'file',
          header: {
            'Authorization': `Bearer ${app.getGlobalToken()}`
          },
          success(res) {
            const {
              data
            } = JSON.parse(res.data)
            me.setData({
              image: data,
              imageUrl: processImageUrl(data)
            })
            wx.showToast({
              title: '上传成功',
              icon: 'success'
            });
          },
          fail: () => {
            wx.showToast({
              title: '上传图片失败',
              icon: 'none'
            })
          }
        })
      }
    })
  },
  // 输入名称
  onNameInput(e) {
    this.setData({ name: e.detail.value });
  },

  // 输入简介
  onShortDescriptionInput(e) {
    this.setData({ shortDescription: e.detail.value });
  },

  // 输入生长周期
  onGrowthCycleInput(e) {
    this.setData({ growthCycle: e.detail.value });
  },

  // 输入详细描述
  onFullDescriptionInput(e) {
    this.setData({ fullDescription: e.detail.value });
  },

  // 输入建议
  onSuggestionInput(e) {
    this.setData({ suggestion: e.detail.value });
  },

  // 输入注意事项
  onPrecautionsInput(e) {
    this.setData({ precautions: e.detail.value });
  },

  // 提交表单
  submitForm() {
    const { name, image, shortDescription, growthCycle, fullDescription, suggestion, precautions } = this.data;

    // 表单验证
    if (!name) {
      wx.showToast({
        title: '请输入名称',
        icon: 'none'
      });
      return;
    }

    if (!image) {
      wx.showToast({
        title: '请上传图片',
        icon: 'none'
      });
      return;
    }

    if (!shortDescription) {
      wx.showToast({
        title: '请输入简介',
        icon: 'none'
      });
      return;
    }

    if (!growthCycle) {
      wx.showToast({
        title: '请输入生长周期',
        icon: 'none'
      });
      return;
    }

    if (!fullDescription) {
      wx.showToast({
        title: '请输入详细描述',
        icon: 'none'
      });
      return;
    }

    if (!suggestion) {
      wx.showToast({
        title: '请输入建议',
        icon: 'none'
      });
      return;
    }

    if (!precautions) {
      wx.showToast({
        title: '请输入注意事项',
        icon: 'none'
      });
      return;
    }

    // 模拟提交
    wx.showLoading({
      title: '保存中...'
    });

    // 提交表单数据
    request.request({
      url: `${app.globalData.baseUrl}/api/agricultural-knowledge/residues`,
      method: 'POST',
      data: {
        id: this.data.id,
        name: this.data.name,
        image: this.data.image,
        shortDescription: this.data.shortDescription,
        growthCycle: this.data.growthCycle,
        fullDescription: this.data.fullDescription,
        suggestion: this.data.suggestion,
        precautions: this.data.precautions
      },
      header: {
        'Authorization': `Bearer ${app.getGlobalToken()}`
      },
      success: (res) => {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
        app.globalData.needRefresh = true;
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      },
      fail: () => {
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        })
        console.error('保存失败:', err)
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  }
}); 